package com.ken.mall.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisPoolUtil {
    private static Logger logger = LoggerFactory.getLogger(RedisPoolUtil.class);

    @Autowired
    private JedisPool jedisPool;

    public Long expire(String key,int exTime){
        Long result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.expire(key,exTime);
        } catch (Exception e) {
            logger.error("expire key:{} exTime:{} error",key,exTime,e);
            jedisPool.returnBrokenResource(jedis);
            return result;
        }
        jedisPool.returnResource(jedis);
        return result;
    }

    //exTime单位秒
    public String setEx(String key,String value,int exTime){
        String result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.setex(key,exTime,value);
        } catch (Exception e) {
            logger.error("set key:{} value:{} error",key,value,e);
            jedisPool.returnBrokenResource(jedis);
            return result;
        }
        jedisPool.returnResource(jedis);
        return result;
    }

    public String set(String key,String value){
        String result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.set(key,value);
        } catch (Exception e) {
            logger.error("set key:{} value:{} error",key,value,e);
            jedisPool.returnBrokenResource(jedis);
            return result;
        }
        jedisPool.returnResource(jedis);
        return result;
    }

    public String get(String key){
        if (StringUtils.isBlank(key))return null;
        String result = null;
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            result = jedis.get(key);
        } catch (Exception e) {
            logger.error("get key:{}  error",key,e);
            jedisPool.returnBrokenResource(jedis);
            return result;
        }
        jedisPool.returnResource(jedis);
        return result;
    }

    public Long del(String key){
        if (StringUtils.isBlank(key))return null;
        Long result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.del(key);
        } catch (Exception e) {
            logger.error("del key:{} error",key,e);
            jedisPool.returnBrokenResource(jedis);
            return result;
        }
        jedisPool.returnResource(jedis);
        return result;
    }

}
